package com.xingxue.logistics.common.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 生成验证码的工具类
 * @author Kris at 2018/9/30 10:21
 */
public class CodeImage {

    static String str = "abcdefghijklmnopqrstuvwxyz";
    static char[] chars = (str+str.toUpperCase()+"0123456789").toCharArray();

    static int code_length = 6;
    static int width = 120;
    static int height = 30;
    static int lineNum = 3;

    static Random random = new Random();

    /**
     * 创建图形验证码
     * @return obj[0]为验证码字符串。
     *          obj[1]为图形验证码类型是BufferedImage
     */
    public static Object[] createCodeImage(){
        Object[] result = new Object[2];
        String codeStr = CommonUtils.createCodeStr(code_length,chars);
        result[0] = codeStr;
        BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //画布
        Graphics2D g = bi.createGraphics();
        //背景色
        /*g.setBackground(Color.white);*/
        //设置笔刷白色
        g.setColor(Color.WHITE);
        //填充整个屏幕 (x,y,w,h)
        g.fillRect(0,0,width,height);
        //画入字符串
        for(int i=0;i<codeStr.length();i++){
            String s = codeStr.substring(i,i+1);
            g.setFont(new Font("宋体",Font.BOLD,20+random.nextInt(10)));
            g.setColor(new Color(random.nextInt(88),random.nextInt(188),random.nextInt(255)));
            g.drawString(s,20*i, 22+random.nextInt(5));
        }
        //画干扰线
        for(int i=0;i<lineNum;i++){
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            g.drawLine(random.nextInt(10),random.nextInt(height),width*3/2+random.nextInt(width/3),random.nextInt(height));
        }

        //释放
        g.dispose();
        result[1] = bi;
        return result;
    }


}
